package com.itheima.controller;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.itheima.common.R;
import com.itheima.entity.Employee;
import com.itheima.service.EmployeeService;

import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.util.DigestUtils;
import org.springframework.web.bind.annotation.*;

import javax.servlet.http.HttpServletRequest;

@Slf4j
@RestController
@RequestMapping("/employee")
public class EmployeeController {

    @Autowired
    private EmployeeService employeeService;

    /**
     * 员工登录
     * @param req
     * @param emp
     * @return
     */
    @PostMapping("login")
    public R<Employee> Login(HttpServletRequest req, @RequestBody Employee emp){
        //1.将页面提交的密码password进行md5加密
        String password = emp.getPassword();
        String pwd = DigestUtils.md5DigestAsHex(password.getBytes());
        log.info("加密后的密码{}",pwd);

        //2.根据页面提交的用户名username查询数据库
        String username = emp.getUsername();
        log.info("页面提交的用户名{}",username);

        LambdaQueryWrapper<Employee> queryWrapper = new LambdaQueryWrapper<>();
        queryWrapper.eq(Employee::getUsername,username);
        Employee user = employeeService.getOne(queryWrapper);
        log.info("根据条件查询出的{}数据",user);

        //3.如果没有查询到用户返回登录失败
        if (user == null){
            return R.error("该用户名未注册");

        }

        //4.判断密码是否一致
        if (!user.getPassword().equals(pwd)){
            return R.error("密码错误，请重新输入");
        }

        //5.查看员工状态是否已禁用
        if(user.getStatus() == 0){
            return R.error("该账号已被禁用，请联系管理员");
        }

        //6.将员工id放入Session，返回登录成功结果
        req.getSession().setAttribute("employee",user.getId());

        return R.success(user);
    }

    /**
     * 员工退出
     * @param request
     * @return
     */
    @PostMapping("/logout")
    public R<String> logout(HttpServletRequest request){
        //清理session中保存的当前登录的员工的id
        request.getSession().removeAttribute("employee");
        return R.success("退出成功");
    }

    /**
     * 新增员工
     * @param request
     * @param employee
     * @return
     */
    @PostMapping
    public R<String> save(HttpServletRequest request,@RequestBody Employee employee){
        //设置初始密码，并进行md5加密
        String pwd = DigestUtils.md5DigestAsHex("123456".getBytes());
        employee.setPassword(pwd);
        //设置创建时间和更新时间
//        LocalDateTime now = LocalDateTime.now();
//        employee.setCreateTime(now);
//        employee.setUpdateTime(now);
        //设置创建人和更新人
//        Long user = (Long) request.getSession().getAttribute("employee");
//        employee.setCreateUser(user);
//        employee.setUpdateUser(user);
        employeeService.save(employee);
        log.info("新增员工成功{}",employee);
        return R.success("新增员工成功");
    }

    /**
     * 分页查询
     * @param page
     * @param pageSize
     * @param name
     * @return
     */
    @GetMapping("/page")
    public R<Page> page(int page, int pageSize, String name){
        log.info("page={}, pageSize={}, name={}",page,pageSize,name);
        //构造分页构造器
        Page pageInfo = new Page(page,pageSize);

        //构造条件构造器
        LambdaQueryWrapper<Employee> lqw = new LambdaQueryWrapper();
        //添加过条件
        lqw.like(name!=null,Employee::getName,name);
        //添加排序条件
        lqw.orderByDesc(Employee::getUpdateTime);
        //执行查询
        employeeService.page(pageInfo,lqw);
        return R.success(pageInfo);
    }

    /**
     * 修改员工（包括启用禁用）
     * @param request
     * @param employee
     * @return
     */
    @PutMapping
    public R<String> update(HttpServletRequest request, @RequestBody Employee employee){
//        Long employee1 = (Long) request.getSession().getAttribute("employee");
        log.info("请求参数{}",employee.toString());
//        employee.setUpdateTime(LocalDateTime.now());
//        employee.setUpdateUser(employee1);
        employeeService.updateById(employee);
        return R.success("修改成功");
    }

    /**
     * 根据id查询员工
     * @param id
     * @return
     */
    @GetMapping("/{id}")
    public R<Employee> getById(@PathVariable Long id){
        Employee employee = employeeService.getById(id);
        log.info(employee.toString());
        return R.success(employee);
    }

}
